const Base = require('./base.js');
const common = require('../../common/common.js');
const moment = require('moment');
module.exports = class extends Base {
    async indexAction() {//查询
        const page = this.get('page') || 1;
        const size = this.get('size') || 10;
        const name = this.get('name') || '';
        const id = this.get('id') || '';
        const keywords = this.get('keywords') || '';
        const sortField = this.get('sortfield') || 'integral';

        const model = this.model('tag');
        let seachdata = {};
        if (name) {
            seachdata.name = ['like', `%${name}%`];
        }
        if (id) {
            seachdata.id = id;
        }
        let list = await model.where(seachdata).order([sortField]).page(page, size).countSelect();
        return this.success(list);
    }
    async getTagsAction() {
        const model = this.model('tag');
        let data = await model.select();
        data = common.listToTree(data);
        return this.success(data);
    }

    async getUserTagsAction() {//用户点击标签
        const model = this.model('tag');
        let uid = this.post('uid') || 0;
        if (uid<1) {
            return this.fail(400, '请选择用户');
        }
        let data = await model.select();
        const tagids = await this.model('user_tag').where({user_id:uid}).getField('tag_id');
        let usertags = [];
        if(!think.isEmpty(tagids)){
            usertags = await this.model('tag').where({id:['in',tagids]}).select();
        }
        for (let item of data) {
            item.checked = false;
            if (tagids && tagids.includes(item.id)) item.checked = true;
        }
        data = common.listToTree(data);
        return this.success({
            tags:data,
            usertags:usertags
        });
    }
    /**
     * 保存
     */
    async saveAction() {
        if (!this.isPost) {
            return false;
        }
        const values = this.post();
        const name = this.post('name');
        let id = this.post('id') || 0;
        const pid = this.post('pid') || 0;
        const model = this.model('tag');
        let data = await model.where({ id: ['<>', id], name: name, pid: pid }).find();
        if (!think.isEmpty(data)) {
            return this.fail(400, '名称重复');
        }
        values['update_id'] = think.userId;
        if (id > 0) {
            values['update_time'] = Math.floor((new Date()).getTime() / 1000);
            delete values.id;
            await model.where({ id: id }).update(values);
        } else {
            values['add_time'] = Math.floor((new Date()).getTime() / 1000);
            delete values.id;
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }

    async saveTagAction() {
        if (!this.isPost) {
            return false;
        }
        const values = this.post();
        let id = this.post('id') || 0;
        const pid = this.post('pid') || 0;
        const name = this.post('name')||'';
        const model = this.model('tag');
        let data = await model.where({ id: ['<>', id], name: name, pid: pid }).find();
        if (!think.isEmpty(data)) {
            return this.fail(400, '名称重复');
        }
        values['update_id'] = think.userId;
        if (id > 0) {
            values['update_time'] = Math.floor((new Date()).getTime() / 1000);
            delete values.id;
            await model.where({ id: id }).update(values);
        } else {
            values['add_time'] = Math.floor((new Date()).getTime() / 1000);
            delete values.id;
            id = await model.add(values);
            values['id'] = id;
        }
        return this.success(values);
    }

    async addTagAction() {
        if (!this.isPost) {
            return false;
        }
        const values = this.post();
        let id = this.post('id') || 0;
        let uid = this.post('uid') || 0;
        if (uid<1) {
            return this.fail(400, '请选择用户');
        }
        const tag_ids = this.post('tag_ids') || [];
        const model = this.model('user_tag');
        // values['update_id']=think.userId;
        let addData = [];
        if (id > 0) {
            values['update_time'] = Math.floor((new Date()).getTime() / 1000);
            delete values.id;
            await model.where({ id: id }).update(values);
        } else {
            let current = Math.floor((new Date()).getTime() / 1000);
            if (tag_ids.length>0) {

                for (let item of tag_ids) {
                    addData.push({
                        user_id:uid,
                        tag_id:item,
                        update_id:think.userId,
                        add_time:current
                    });
                }
                await model.transaction(async () => {
                    await model.where({ user_id: uid }).delete();
                    await model.addMany(addData);
                });
            }else{
                await model.where({ user_id: uid }).delete();
            }
        }
        return this.success(addData);
    }


async readAction() {
    const model = this.model('tag');
    const id = this.get('id');
    const data = await model.where({ id: id }).find();
    return this.success(data);
}
async updateAction() {
    const model = this.model('tag');
    const values = this.post();
    const name = this.post('name')||'';
    const id = this.post('id') || 0;
    const pid = this.post('pid') || 0;
    let edata = await model.where({ id: ['<>', id], name: name, pid: pid }).find();
    if (!think.isEmpty(edata)) {
        return this.fail(400, '名称重复');
    }
    values['update_id'] = think.userId;
    values['update_time'] = Math.floor((new Date()).getTime() / 1000);
    let data = await model.where({ id: id }).update(values);
    return this.success(data);
}
async deleteAction() {

    const model = this.model('tag');
    const values = this.post();
    const id = this.post('id');
    let edata = await this.model('user_tag').where({ tag_id: id }).find();
    let cdata = await this.model('tag').where({ pid: id }).find();
    if (!think.isEmpty(cdata)) return this.fail(400, '分类含有子标签，无法删除');
    if (!think.isEmpty(edata)) return this.fail(400, '标签正在使用，无法删除');
    let data = await model.where({ id: id }).delete();
    return this.success(data);
}

async staticAction(){//客户统计
    const begin = this.get('begin');
    const end = this.get('end') ;
    if(!begin){
        return this.fail(400, '请输入统计开始时间');
    }
    if(!end){
        return this.fail(400, '请输入统计结束时间');
    }
    let timesearch={};
    if (begin || end) {
        if (begin) {
          timesearch['egt'] = Math.floor(new Date(begin).getTime()/1000);
        }
        if (end) {
          timesearch['lt'] = Math.floor(new Date(end).getTime()/1000);
        }
      }
    const usernew = await this.model('user').where({register_time:timesearch}).count('id');
    const ordernew = await this.model('order').where({add_time:timesearch,is_delete:0}).count('distinct user_id');
    const timeu = await this.model('user').where({register_time:timesearch}).order('register_time').getField('register_time');
    const timeo = await this.model('order').where({add_time:timesearch,is_delete:0}).order('add_time').getField('add_time');
    let timec = timeu.concat(timeo);
    // 去重
    var newArr = [];
    for (var i = 0; i < timec.length; i++) {
      var index = Math.floor(timec[i]/86400)*86400; 
      if( newArr.indexOf(index)==-1){
        newArr.push(index);
      }
    }
    // 排序
    newArr.sort(function (a, b) {
      return a - b;
    })
    let data=[];
    for(let item of newArr){
        data.push({
            date:moment.unix(item).format('YYYY-MM-DD'),
            newuser:await this.model('user').where({register_time:{egt:item,lt:item+86400}}).count('id'),
            neworder:await this.model('order').where({add_time:{egt:item,lt:item+86400}}).count('distinct user_id')
        })
    }
    return this.success({
        usercount:usernew,ordercount:ordernew,
        data:data
    });

}

async selectUserAction(){
    const page = this.post('page') || 1;
    const size = this.post('size') || 10;
    let nickname = this.post('nickname') || '';
    const buffer = Buffer.from(nickname);
    let name = this.post('name') || '';
    let mobile = this.post('mobile') || '';
    let hasPhone = this.post('hasPhone') || 0;
    let tag_ids = this.post('tag_ids') || [];
    let seachdata = {};

    if (name) {
        seachdata.name = ['like', `%${name}%`];
    }
    if (nickname) {
        nickname = buffer.toString('base64');
        seachdata.nickname = ['like', `%${nickname}%`];
    }
    if(mobile&&hasPhone){
        seachdata.mobile = {like: `%${mobile}%`,'!=':''}
    }else if (mobile) {
        seachdata.mobile = ['like', `%${mobile}%`];
    }else if (hasPhone) {
        seachdata.mobile = ['!=', ''];
    }
    if (tag_ids && tag_ids.length > 0) {
        let uids = await this.model('user_tag').where({ tag_id: ['in', tag_ids] }).getField('user_id');
        seachdata.id = ['in', uids];
    }
    const model = this.model('user');
    const data = await model.where(seachdata).order(['id DESC']).page(page, size).countSelect();
    for (const item of data.data) {
        item.register_time = moment.unix(item.register_time).format('YYYY-MM-DD HH:mm:ss');
        item.last_login_time = moment.unix(item.last_login_time).format('YYYY-MM-DD HH:mm:ss');
        item.nickname = Buffer.from(item.nickname, 'base64').toString();
    }
    let info = {
        userData: data,
        userCount: await model.count()
    }
    return this.success(info);
}

};